<template>
  <div class="container">
    <div class="main-content">
      <el-form :model="blogForm" :rules="rules" ref="blogFormRef">
        <el-form-item prop="title">
          <el-input
            v-model="blogForm.title"
            placeholder="请输入标题"
            class="title-input"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item prop="category" class="category-form-item">
          <div class="category-section">
            <span class="label">文章分类：</span>
            <el-select
              v-model="blogForm.category"
              placeholder="请选择分类"
              class="category-select full-width"
            >
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item prop="tags" class="tags-form-item">
          <div class="tags-section">
            <span class="label">文章标签：</span>
            <el-select
              v-model="blogForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              :max-collapse-tags="3"
              placeholder="请选择或输入标签"
              class="tag-select full-width"
            >
              <el-option
                v-for="item in tags"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item prop="content">
          <MdEditor
            v-model="blogForm.content"
            v-profanity-filter
            class="md-editor"
            :toolbars="toolbars"
            :preview="preview"
            @onUploadImg="onUploadImg"
            language="zh-CN"
          />
        </el-form-item>

        <el-form-item>
          <div class="action-buttons">
            <el-button type="primary" @click="handlePublish" :loading="publishing">发布博客</el-button>
            <el-button @click="handleSaveDraft">保存草稿</el-button>
            <el-button
              type="text"
              @click="togglePreview"
              style="display: none;"
            >{{ preview ? "关闭预览" : "开启预览" }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="side-content">
      <el-card class="publish-guide">
        <template #header>
          <div class="card-header">
            <span>Markdown 语法帮助</span>
          </div>
        </template>
        <div class="guide-content">
          <h4>常用语法：</h4>
          <ul>
            <li># 一级标题</li>
            <li>## 二级标题</li>
            <li>**粗体文本**</li>
            <li>*斜体文本*</li>
            <li>[链接文本](URL)</li>
            <li>![图片描述](图片URL)</li>
            <li>```代码块```</li>
          </ul>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { publishBlog, saveDraft } from "@/api/blog";
import { useRouter } from "vue-router";

const blogFormRef = ref(null);
const publishing = ref(false);
const preview = ref(true);
const router = useRouter();

const blogForm = reactive({
  title: "",
  content: "",
  category: "",
  tags: []
});

const toolbars = [
  "bold",
  "underline",
  "italic",
  "strikethrough",
  "-",
  "title",
  "sub",
  "sup",
  "quote",
  "unorderedList",
  "orderedList",
  "-",
  "codeRow",
  "code",
  "link",
  "image",
  "table",
  "-",
  "revoke",
  "next",
  "save",
  "=",
  "preview",
  "htmlPreview",
  "catalog"
];

const categories = reactive([
  { value: "frontend", label: "前端开发" },
  { value: "backend", label: "后端开发" },
  { value: "mobile", label: "移动开发" },
  { value: "algorithm", label: "算法" },
  { value: "database", label: "数据库" },
  { value: "devops", label: "DevOps" },
  { value: "ai", label: "人工智能" }
]);

const tags = reactive([
  { value: "vue", label: "Vue.js" },
  { value: "react", label: "React" },
  { value: "javascript", label: "JavaScript" },
  { value: "typescript", label: "TypeScript" },
  { value: "python", label: "Python" },
  { value: "java", label: "Java" },
  { value: "spring", label: "Spring" }
]);

const rules = {
  title: [
    { required: true, message: "请输入博客标题", trigger: "blur" },
    { min: 2, max: 100, message: "标题长度在2-100个字符之间", trigger: "blur" }
  ],
  category: [{ required: true, message: "请选择文章分类", trigger: "change" }],
  tags: [{ required: true, message: "请选择文章标签", trigger: "change" }],
  content: [
    { required: true, message: "请输入博客内容", trigger: "blur" },
    { min: 10, message: "内容不能少于10个字符", trigger: "blur" }
  ]
};

const togglePreview = () => {
  preview.value = !preview.value;
};

const onUploadImg = async (files, callback) => {
  // TODO: 实现图片上传
  const res = await Promise.all(
    files.map(file => {
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
      });
    })
  );
  callback(res);
};

const handlePublish = async () => {
  if (!blogFormRef.value) return;

  try {
    await blogFormRef.value.validate();
    publishing.value = true;

    const blogData = {
      title: blogForm.title,
      content: blogForm.content,
      category: blogForm.category,
      tags: blogForm.tags
    };

    const res = await publishBlog(blogData);

    if (res.code === "200") {
      ElMessage.success("发布成功");
      // 重置表单并刷新页面
      blogFormRef.value.resetFields();
      window.location.reload();
    }
  } catch (error) {
    console.error("发布失败:", error);
    ElMessage.error(error.message || "发布失败");
  } finally {
    publishing.value = false;
  }
};

const handleSaveDraft = async () => {
  try {
    const draftData = {
      title: blogForm.title,
      content: blogForm.content,
      category: blogForm.category,
      tags: blogForm.tags
    };

    const res = await saveDraft(draftData);
    if (res.code === "200") {
      ElMessage.success("保存草稿成功");
    }
  } catch (error) {
    console.error("保存草稿失败:", error);
    ElMessage.error(error.message || "保存草稿失败");
  }
};

const handleCategoryChange = value => {
  // 根据选中的value找到对应的分类对象
  const selectedCategory = categories.find(item => item.value === value);
  if (selectedCategory) {
    blogForm.category = selectedCategory.value;
  }
};
</script>

<style scoped lang="scss">
.container {
  display: flex;
  gap: 20px;
  padding: 20px 0;
}

.main-content {
  flex: 1;
  min-width: 0;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.side-content {
  width: 300px;
  flex-shrink: 0;
}

.title-input {
  margin-bottom: 20px;
}

:deep(.md-editor) {
  height: 640px;
  margin-bottom: 20px;
}

.publish-guide {
  .card-header {
    font-weight: bold;
  }

  .guide-content {
    h4 {
      margin: 16px 0 8px;
      color: #333;
    }

    ul {
      margin: 0;
      padding-left: 20px;
      color: #666;

      li {
        margin-bottom: 8px;
        font-size: 14px;
      }
    }
  }
}

.category-form-item,
.tags-form-item {
  margin-bottom: 20px;
  box-sizing: border-box;
}

.category-section,
.tags-section {
  width: 100%;
  display: flex;
  align-items: center;
}

.label {
  white-space: nowrap;
  color: #606266;
  width: 80px;
}

:deep(.el-select .el-select__tags) {
  flex-wrap: wrap;
}

.label {
  margin-right: 10px;
}

.full-width {
  width: calc(100% - 100px);
}
</style>
